package models

import (
	"fmt"
	"strconv"

	"github.com/gin-gonic/gin"
)

type MyError struct {
	Msg string
}

func (e MyError) Error() string {
	return fmt.Sprintf("Error: %s", e.Msg)
}

// 获取params，返回int类型
func GetParamsInt(c *gin.Context, name string) (int, error) {
	paramvalue, bool := c.Params.Get(name)
	if !bool {
		return 0, MyError{Msg: "parameter not found: " + name}
	}
	value, err := strconv.Atoi(paramvalue)
	if err != nil {
		return 0, MyError{Msg: "invalid integer value: " + paramvalue}
	}
	return value, nil
}

type PageInfo struct {
	Page int
	Size int
}

// 获取分页
func GetPageInfo(c *gin.Context) (*PageInfo, error) {
	page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err != nil || page < 1 {
		return nil, MyError{Msg: "invalid integer value: " + c.Query("page")}
	}
	size, err := strconv.Atoi(c.DefaultQuery("size", "10"))
	if err != nil || size < 1 {
		return nil, MyError{Msg: "invalid integer value: " + c.Query("size")}
	}
	return &PageInfo{Page: page, Size: size}, nil
}
